#define _CRT_SECURE_NO_WARNINGS 1


class Solution
{
    vector<vector<int>> ret;
    vector<int> path;
    vector<int> visit;
public:
    vector<vector<int>> permute(vector<int>& nums)
    {
        visit.resize(nums.size());
        dfs(nums);
        return ret;
    }

    void dfs(vector<int>& nums)
    {
        if (path.size() == nums.size())
        {
            ret.push_back(path);
            return;
        }

        for (int i = 0; i < nums.size(); ++i)
        {
            if (visit[i] == false)
            {
                visit[i] = true;
                path.push_back(nums[i]);
                dfs(nums);
                path.pop_back();
                visit[i] = false;
            }

        }
    }
};
class Solution
{
    vector<vector<int>> ret;
    vector<int> path;
    vector<bool> visit;
    int n;
public:
    vector<vector<int>> permuteUnique(vector<int>& nums)
    {
        n = nums.size();
        visit.resize(n);
        sort(nums.begin(), nums.end());
        dfs(nums);
        return ret;
    }

    void dfs(vector<int>& nums)
    {
        if (path.size() == n)
        {
            ret.push_back(path);
            return;
        }

        for (int i = 0; i < n; ++i)
        {
            if (visit[i] == false && (i == 0 || nums[i] != nums[i - 1] || visit[i - 1] == true))
            {
                visit[i] = true;
                path.push_back(nums[i]);
                dfs(nums);
                visit[i] = false;
                path.pop_back();
            }
        }
    }
};